#include "stdafx.h"
#include "Table.h"
#include "Column.h"

using namespace ese;

bool table::detect_columns()
{
	m_columns.clear();
	m_columns_by_name.clear();
	JET_COLUMNLIST cl;

	cl.cbStruct = sizeof(cl);

	m_last_error = JetGetTableColumnInfoA(database().session().id(), id(), nullptr, &cl, sizeof(cl), JET_ColInfoListSortColumnid);
	if (JET_errSuccess != m_last_error)
	{
		return false;
	}// if

	table t(m_db, cl.tableid);
	m_columns.reserve(cl.cRecord);

	database().session().begin_transaction();
	try
	{
		char buffer[256];
		unsigned long size = 256;
		m_last_error = ::JetMove(database().session().id(), t.id(), JET_MoveFirst, 0);
		int index = 0;

		while (m_last_error == JET_errSuccess)
		{
			m_last_error = ::JetRetrieveColumn(database().session().id(), t.id(), cl.columnidDefinitionName, buffer, 256, &size, 0, nullptr);
			if (m_last_error == JET_errSuccess)
			{
				buffer[size] = 0;
				std::unique_ptr<ese::column> c(new ese::column(*this, buffer));
				if (c->exists())
				{
					m_columns.push_back(std::shared_ptr<ese::column>(c.get()));
					c.release();
					m_columns_by_name[buffer] = index++;
				}// if
			}// if
			m_last_error = ::JetMove(database().session().id(), t.id(), JET_MoveNext, 0);
		}// while
	}//try
	catch (...)
	{
	}// catch
	database().session().commit();

	return true;
}

bool table::create_column(const char *name, const JET_COLTYP columnType, const JET_GRBIT grbit, const unsigned long maxSize)
{
	return ese::column(*this, name, columnType, grbit, maxSize).create();
}
